<?php

class ProductController extends BackendController
{
	public $parentUrl;
	
	public function init(){
		parent::init();
		$this->parentUrl = $this->module->id . '/' . Yii::app()->getController()->getId();
	}

	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view','upload'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update','upload'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete','upload'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	public function actionCreate()
	{
		try {
            $model = new Product();            
            if (isset($_POST['Product'])) {
                $model->attributes = $_POST['Product'];
                $model->ProductNameRewrite = str_replace(" ", "-", strtolower(StringHelper::remove_vietnamese_accents($model->ProductName)));
				$model->SoldQuantity = 0;
				$model->CreateDate = date('Y-m-d H:i:s');
				$model->UpdateDate = date('Y-m-d H:i:s');
                // status 0 is Open.
                $cover_image = CUploadedFile::getInstance($model, 'CoverPhoto');
                if ($cover_image)
                    $model->CoverPhoto = 'cover_' . md5(time()) . '.' . $cover_image->getExtensionName();
                $model->validate();
                if (!$model->hasErrors()) {
                    if ($cover_image) {
                        $model->CoverPhoto = MyFunctionCustom::saveCover($model, $cover_image);
                    }
                    if ($model->save()){
                        $this->redirect(Yii::app()->createAbsoluteUrl(Yii::app()->baseUrl . '/store/backend/product/index'));
                    }
                }
            }

            $this->render('create', array(
                'model' => $model
            ));
        } catch (Exception $e) {
            Yii::log("Invalid request. Please do not repeat this request again.");
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
        }
	}

	

	public function actionUpdate($id)
	{
		try {
            $model = $this->loadModel($id);
            if (isset($_POST['Product'])) {
            	$oldCover = $model->CoverPhoto;
                $model->attributes = $_POST['Product'];
				$model->ProductNameRewrite = str_replace(" ", "-", strtolower(StringHelper::remove_vietnamese_accents($model->ProductName)));
				$model->UpdateDate = date('Y-m-d H:i:s');
                $cover_image = CUploadedFile::getInstance($model,'CoverPhoto');
                if ($cover_image)
                    $model->CoverPhoto = 'cover_' . md5(time()) . '.' . $cover_image->getExtensionName();
                else{
                	$model->CoverPhoto = $oldCover;
                }
                $model->validate();
                if (!$model->hasErrors()) {
                    if ($cover_image) {
                        //delete File
                        MyFunctionCustom::DeleteFile($model, 'CoverPhoto', 'cover');
                        $model->CoverPhoto = MyFunctionCustom::saveCover($model, $cover_image);
                    }

                    if ($model->save())
                        $this->redirect(Yii::app()->createAbsoluteUrl(Yii::app()->baseUrl . '/store/backend/product/index'));
                }
            }
            $this->render('update', array(
                'model' => $model,
                'parentUrl' => $this->parentUrl
            ));
        } catch (Exception $e) {
            Yii::log("Invalid request. Please do not repeat this request again.");
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
        }

	}


	public function actionDelete()
	{
		$model = Product::model()->findByPk($_POST['id']);
		if(isset($model)){
			if($this->loadModel($_POST['id'])->delete())
				echo CJSON::encode(1);
		}

	}

	public function actionIndex()
	{
		try{
			$model = new Product();
			$data = $model->getAll();
			$this->render('index',array(
				'data' => $data,
				'parentUrl' => $this->parentUrl));
		}catch(Exception $e){
			echo "Da xay ra loi";
			die;
		}
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Product('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Product']))
			$model->attributes=$_GET['Product'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Product the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		try {
            $model = Product::model()->findByPk($id);
            if ($model === null)
                throw new CHttpException(404, 'The requested page does not exist.');
            return $model;
        } catch (Exception $e) {
            Yii::log("Invalid request. Please do not repeat this request again.");
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
        }

	}

	/**
	 * Performs the AJAX validation.
	 * @param Product $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='product-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}

	// public function actionAjaxDelete()
	// {
	//     if (!YII_DEBUG && !Yii::app()->request->isAjaxRequest) {
	//         throw new CHttpException('403', 'Forbidden access.');
	//     }
	//     if (empty($_GET['term'])) {
	//         throw new CHttpException('404', 'Missing "term" GET parameter.');
	//     }
	//     $term = $_GET['term'];
	//     $filters = empty($_GET['exclude']) ? null : (int) $_GET['exclude']);
	//     header('Content-Type: application/json; charset="UTF-8"');
	//     echo json_encode(User::completeTerm($term, $exclude));
	//     Yii::app()->end();
	// }

}
